<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>维修工订单管理 - 家电维修系统</title>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/all.min.css}" rel="stylesheet">

    <style>
        .dashboard-container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .order-card {
            margin-bottom: 20px;
            transition: all 0.3s;
        }
        .order-card:hover {
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .status-badge {
            font-size: 0.9em;
        }
        #map {
            height: 400px;
            width: 100%;
            margin-bottom: 20px;
        }
        .map-container {
            display: none;
            margin-top: 20px;
        }
        .navigation-info {
            margin-top: 10px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 5px;
            display: none;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container">
        <a class="navbar-brand" href="#">维修工工作台</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link active" href="/repairman">工作台</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" active href="/repairman/orders">我的订单</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/repairman/profile">个人资料</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/repairman-announcements">公告</a>
                </li>
            </ul>
            <div class="d-flex">
                <span class="navbar-text me-3" id="userInfo"></span>
                <button class="btn btn-outline-light" onclick="logout()">退出</button>
            </div>
        </div>
    </div>
</nav>


<div class="container mt-4">
        <div class="dashboard-container">
            <!-- 添加统计卡片 -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body text-center">
                            <h3 class="card-title" id="totalOrders">0</h3>
                            <p class="text-muted">总订单数</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body text-center">
                            <h3 class="card-title" id="completedOrders">0</h3>
                            <p class="text-muted">已完成订单</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body text-center">
                            <h3 class="card-title" id="pendingOrders">0</h3>
                            <p class="text-muted">待处理订单</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body text-center">
                            <h3 class="card-title" id="todayOrders">0</h3>
                            <p class="text-muted">今日订单</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row mb-4">
                <div class="col">
                    <h4>我的订单</h4>
                </div>
                <div class="col-auto">
                    <div class="btn-group">
                        <button class="btn btn-outline-primary" onclick="filterOrders('all')">全部</button>
                        <button class="btn btn-outline-primary" onclick="filterOrders('pending')">待接单</button>
                        <button class="btn btn-outline-primary" onclick="filterOrders('accepted')">已接单</button>
                        <button class="btn btn-outline-primary" onclick="filterOrders('fixing')">维修中</button>
                        <button class="btn btn-outline-primary" onclick="filterOrders('completed')">已完成</button>
                        <button class="btn btn-outline-primary" onclick="filterOrders('canceled')">已取消</button>
                    </div>
                </div>
            </div>

            <div id="orderList">
                <!-- 订单列表将通过JavaScript动态加载 -->
            </div>
        </div>
    </div>

    <!-- 订单详情模态框 -->
    <div class="modal fade" id="orderModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">订单详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div id="orderDetails">
                                <!-- 订单详情将通过JavaScript动态加载 -->
                            </div>
                            <!-- 添加上传轨迹按钮 -->
                            <div id="trackingControls" class="mt-3" style="display: none;">
                                <button type="button" class="btn btn-info" onclick="uploadCurrentLocation()">
                                    <i class="fas fa-location-arrow"></i> 上传当前位置
                                </button>
                                <small class="text-muted d-block mt-2">点击按钮上传您的当前位置到系统</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div id="orderMap" style="height: 400px; width: 100%;">
                                <!-- 地图将在这里显示 -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="actionButton" onclick="handleOrderAction()"></button>
                </div>
            </div>
        </div>
    </div>

    <script th:src="@{/js/jquery.min.js}"></script>
    <script th:src="@{/js/bootstrap.bundle.min.js}"></script>
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=spEZ8x14LoDN10ejoQD7GdxOEJYOwqcw"></script>
    <script th:src="@{/js/chart.js}"></script>
    <script src="/js/request.js"></script>
    <script>
        let currentUser = null;
        let currentOrder = null;
        let orderModal = null;
        let map = null;
        let orderMap = null;
        let marker = null;
        let walking = null;
        let orderWalking = null;
        let watchId = null;
        let currentPosition = null;
        let currentLocation = null;
        let currentMarker = null;
        let destinationMarker = null;
        let walkingRoute = null;
        let userAddress = null;
        let trackingInterval;
        let simulationInterval;
        let trackPoints = [];
        const UPLOAD_INTERVAL = 10000; // 10秒上传一次位置
        const SIMULATION_INTERVAL = 1000; // 1秒更新一次模拟位置
        const TOTAL_SIMULATION_TIME = 600000; // 10分钟模拟时间

        // 初始化订单详情地图
        function initOrderMap() {
            orderMap = new BMap.Map("orderMap");
            const point = new BMap.Point(116.404, 39.915);
            orderMap.centerAndZoom(point, 12);
            orderMap.enableScrollWheelZoom(true);

            // 创建步行路线规划实例
            orderWalking = new BMap.WalkingRoute(orderMap, {
                renderOptions: {
                    map: orderMap,
                    autoViewport: true
                }
            });

            getUserLocation();

            // 获取用户位置并规划路线
            if (userAddress && currentOrder) {
                orderWalking.search(userAddress, currentOrder.address);
            }
        }

        // 从用户资料获取位置
        function getUserLocation() {
            const token = localStorage.getItem('token');
            $.ajax({
                url: '/api/repairman/profile',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(response) {
                    if (response.address) {
                        userAddress = response.address;
                    }
                }
            });
        }

        // 更新位置并刷新地图
        function updateLocationAndMap(lng, lat) {
            currentLocation = {
                lng: parseFloat(lng),
                lat: parseFloat(lat)
            };

            const point = new BMap.Point(lng, lat);

            // 更新位置到服务器
            updateLocation(lat, lng);

            // 在地图上显示当前位置
            if (currentMarker) {
                map.removeOverlay(currentMarker);
            }
            currentMarker = new BMap.Marker(point);
            map.addOverlay(currentMarker);
            map.centerAndZoom(point, 15);
        }

        // 获取用户信息
        function getUserInfo() {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login';
                return;
            }

            $.ajax({
                url: '/api/repairman/profile',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(response) {
                    currentUser = response;
                    $('#userInfo').text('欢迎，' + response.realName);
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        localStorage.removeItem('token');
                        window.location.href = '/login';
                    }
                }
            });
        }

        // 加载订单列表
        function loadOrders(status = 'all') {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login';
                return;
            }

            // 显示加载提示
            const orderList = $('#orderList');
            orderList.html('<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>');

            // 根据不同的状态使用不同的URL和参数
            let url = '/api/repairman/orders';
            let params = {};

            switch(status) {
                case 'pending':
                    params.status = '0'; // 待接单状态
                    break;
                case 'accepted':
                    params.status = '1'; // 已接单状态
                    break;
                case 'fixing':
                    params.status = '2'; // 已接单状态
                    break;
                case 'completed':
                    params.status = '3'; // 已完成状态
                    break;
                case 'canceled':
                    params.status = '4'; // 已接单状态
                    break;
                default:
                    // 全部订单不需要status参数
                    break;
            }

            // 调用API获取订单列表
            $.ajax({
                url: url,
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                data: params,
                success: renderOrders,
                error: handleOrderError
            });
        }

        // 提取获取附近订单的函数
        function fetchNearbyOrders(url, token) {
            const params = {
                latitude: currentLocation.lat,
                longitude: currentLocation.lng,
                radius: 5000 // 5000米范围内的订单
            };

            $.ajax({
                url: url,
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                data: params,
                success: renderOrders,
                error: function(xhr) {
                    console.error('Error fetching nearby orders:', xhr);
                    if (xhr.status === 400) {
                        // 如果获取附近订单失败，回退到获取全部订单
                        fetchOrders('/api/repairman/orders', token, 'all');
                    } else {
                        handleOrderError(xhr);
                    }
                }
            });
        }

        // 提取获取订单的函数
        function fetchOrders(url, token, status) {
            $.ajax({
                url: url,
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                data: status === 'all' ? {} : { status: status },
                success: renderOrders,
                error: handleOrderError
            });
        }

        // 渲染订单列表
        function renderOrders(response) {
            const orderList = $('#orderList');
            orderList.empty();

            if (!response || response.length === 0) {
                orderList.append(`
                    <div class="alert alert-info">
                        暂无订单数据
                    </div>
                `);
                return;
            }

            response.forEach(order => {
                const statusMap = {
                    0: { text: '待接单', class: 'warning' },
                    1: { text: '已接单', class: 'info' },
                    2: { text: '维修中', class: 'primary' },
                    3: { text: '已完成', class: 'success' },
                    4: { text: '已取消', class: 'danger' }
                };

                const status = statusMap[order.status] || { text: '未知', class: 'secondary' };

                orderList.append(`
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <h5 class="card-title mb-0">${order.appliance_type}</h5>
                                <span class="badge bg-${status.class}">${status.text}</span>
                            </div>
                            <p class="card-text">故障描述：${order.description}</p>
                            <p class="card-text">地址：${order.address}</p>
                            <p class="card-text">预约时间：${new Date(order.appointment_time).toLocaleString()}</p>
                            <div class="d-flex justify-content-end">
                                <button class="btn btn-primary btn-sm" onclick="showOrderDetails(${order.id})">
                                    查看详情
                                </button>
                                ${(order.status === 1 || order.status === 2) ? `
                                    <button class="btn btn-success btn-sm ms-2" onclick="showMap(${JSON.stringify(order)})">
                                        导航
                                    </button>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                `);
            });
        }

        // 处理订单加载错误
        function handleOrderError(xhr) {
            if (xhr.status === 401) {
                localStorage.removeItem('token');
                window.location.href = '/login';
            } else {
                alert('加载订单失败：' + xhr.responseText);
            }
        }

        // 显示订单详情
        function showOrderDetails(orderId) {
            const token = localStorage.getItem('token');
            $.ajax({
                url: `/api/repairman/orders/${orderId}`,
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(response) {
                    currentOrder = response;
                    const details = $('#orderDetails');
                    details.empty();

                    const statusMap = {
                        0: { text: '待接单', class: 'warning' },
                        1: { text: '已接单', class: 'info' },
                        2: { text: '维修中', class: 'primary' },
                        3: { text: '已完成', class: 'success' },
                        4: { text: '已取消', class: 'danger' }
                    };

                    const status = statusMap[response.status] || { text: '未知', class: 'secondary' };

                    details.html(`
                        <div class="mb-3">
                            <h6>订单信息</h6>
                            <p>订单号：${response.id}</p>
                            <p>状态：<span class="badge bg-${status.class}">${status.text}</span></p>
                            <p>家电类型：${response.appliance_type}</p>
                            <p>故障描述：${response.description}</p>
                            <p>地址：${response.address}</p>
                            <p>预约时间：${new Date(response.appointment_time).toLocaleString()}</p>
                        </div>
                        <div class="mb-3">
                            <h6>用户信息</h6>
                            <p>姓名：${response.userName}</p>
                            <p>电话：${response.userPhone}</p>
                        </div>
                    `);

                    const actionButton = $('#actionButton');
                    actionButton.show();

                    // 显示或隐藏轨迹上传按钮
                    const trackingControls = $('#trackingControls');
                    if (response.status === 2) { // 维修中状态显示轨迹上传按钮
                        trackingControls.show();
                    } else {
                        trackingControls.hide();
                    }

                    switch (response.status) {
                        case 0:
                            actionButton.text('接单').removeClass('btn-success').addClass('btn-primary');
                            break;
                        case 1:
                            actionButton.text('开始维修').removeClass('btn-success').addClass('btn-primary');
                            break;
                        case 2:
                            actionButton.text('完成维修').removeClass('btn-primary').addClass('btn-success');
                            break;
                        default:
                            actionButton.hide();
                    }

                    // 如果是已接单或维修中状态，显示导航信息
                    if (response.status === 1 || response.status === 2) {
                        showOrderMap(response);
                    }

                    orderModal.show();
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        localStorage.removeItem('token');
                        window.location.href = '/login';
                    }
                }
            });
        }

        // 显示订单地图
        function showOrderMap(order) {
            if (!orderMap) {
                initOrderMap();
            }

            // 清除之前的标记和路线
            orderMap.clearOverlays();

            // 如果是维修中状态，显示轨迹点
            if (order.status === 2 && trackPoints.length > 0) {
                // 显示轨迹线
                const polyline = new BMap.Polyline(trackPoints, {
                    strokeColor: "#18a45b",
                    strokeWeight: 4,
                    strokeOpacity: 0.8
                });
                orderMap.addOverlay(polyline);
                
                // 显示当前位置
                if (currentPosition) {
                    const point = new BMap.Point(currentPosition.lng, currentPosition.lat);
                    currentMarker = new BMap.Marker(point);
                    orderMap.addOverlay(currentMarker);
                }
            }

            // 显示目的地标记
            const destPoint = new BMap.Point(order.longitude, order.latitude);
            destinationMarker = new BMap.Marker(destPoint);
            orderMap.addOverlay(destinationMarker);
            orderMap.centerAndZoom(destPoint, 15);

            // 如果已有用户地址，规划路线
            if (userAddress && order.status === 1) {
                orderWalking.search(userAddress, order.address);
            }
        }

        // 处理订单操作
        function handleOrderAction() {
            if (!currentOrder) return;

            const token = localStorage.getItem('token');
            let url, method;

            if (currentOrder.status === 0) {
                // 接单
                url = `/api/repairman/orders/${currentOrder.id}/accept`;
                method = 'POST';
            } else if (currentOrder.status === 1) {
                // 开始维修
                url = `/api/repairman/orders/${currentOrder.id}/start`;
                method = 'POST';
            } else if (currentOrder.status === 2) {
                // 完成维修
                url = `/api/repairman/orders/${currentOrder.id}/complete`;
                method = 'POST';
            }

            $.ajax({
                url: url,
                type: method,
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function() {
                    if (currentOrder.status === 1) {
                        // 开始维修时启动轨迹跟踪
                        startTracking();
                        $('#actionButton').text('完成维修').removeClass('btn-primary').addClass('btn-success');
                        currentOrder.status = 2;
                    } else if (currentOrder.status === 2) {
                        // 完成维修时停止轨迹跟踪
                        stopTracking();
                        orderModal.hide();
                    } else {
                        orderModal.hide();
                    }
                    loadOrders();
                },
                error: function(xhr) {
                    alert('操作失败：' + xhr.responseText);
                }
            });
        }

        // 添加轨迹跟踪相关函数
        function startTracking() {
            // 使用维修工地址作为起始位置
            const myGeo = new BMap.Geocoder();
            myGeo.getPoint(userAddress, function(startPoint) {
                if (startPoint) {
                    currentPosition = {
                        lat: startPoint.lat,
                        lng: startPoint.lng
                    };
                } else {
                    // 如果无法获取维修工地址坐标，使用默认坐标（北京）
                    currentPosition = {
                        lat: 39.915,
                        lng: 116.404
                    };
                }
                
                // 开始模拟移动
                startSimulation();
                
                // 开始定时上传位置
                trackingInterval = setInterval(uploadLocation, UPLOAD_INTERVAL);
            });
        }

        function startSimulation() {
            const destinationPosition = {
                lat: currentOrder.latitude,
                lng: currentOrder.longitude
            };
            
            const steps = TOTAL_SIMULATION_TIME / SIMULATION_INTERVAL;
            const latStep = (destinationPosition.lat - currentPosition.lat) / steps;
            const lngStep = (destinationPosition.lng - currentPosition.lng) / steps;
            let stepCount = 0;

            simulationInterval = setInterval(() => {
                stepCount++;
                if (stepCount >= steps) {
                    clearInterval(simulationInterval);
                    // 到达目的地时发送 ARRIVED 状态
                    $.ajax({
                        url: '/api/repair-track',
                        type: 'POST',
                        contentType: 'application/json',
                        headers: {
                            'Authorization': 'Bearer ' + localStorage.getItem('token')
                        },
                        data: JSON.stringify({
                            orderId: currentOrder.id,
                            repairmanId: currentUser.id,  // 添加维修工ID
                            latitude: destinationPosition.lat,
                            longitude: destinationPosition.lng,
                            status: 'ARRIVED',
                            address: currentOrder.address  // 添加地址信息
                        })
                    });
                    return;
                }

                // 更新当前位置
                currentPosition.lat += latStep;
                currentPosition.lng += lngStep;

                // 更新地图上的标记
                updateCurrentMarker();

                // 更新预计到达时间
                updateEstimatedTime(stepCount, steps);
            }, SIMULATION_INTERVAL);
        }

        function updateCurrentMarker() {
            if (currentMarker) {
                orderMap.removeOverlay(currentMarker);
            }
            const point = new BMap.Point(currentPosition.lng, currentPosition.lat);
            currentMarker = new BMap.Marker(point);
            orderMap.addOverlay(currentMarker);
            
            // 添加到轨迹点数组
            trackPoints.push(point);
            
            // 更新轨迹线
            if (trackPoints.length > 1) {
                const polyline = new BMap.Polyline(trackPoints, {
                    strokeColor: "#18a45b",
                    strokeWeight: 4,
                    strokeOpacity: 0.8
                });
                orderMap.addOverlay(polyline);
            }
        }

        function updateEstimatedTime(current, total) {
            const remainingSteps = total - current;
            const remainingMinutes = Math.ceil((remainingSteps * SIMULATION_INTERVAL) / 60000);
            $('#estimatedTime').text(`约${remainingMinutes}分钟`);
        }

        function uploadLocation() {
            if (!currentOrder || !currentPosition) return;
            
            $.ajax({
                url: '/api/repair-track',
                type: 'POST',
                contentType: 'application/json',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                },
                data: JSON.stringify({
                    orderId: currentOrder.id,
                    repairmanId: currentUser.id,  // 添加维修工ID
                    latitude: currentPosition.lat,
                    longitude: currentPosition.lng,
                    status: 'IN_TRANSIT',  // 在移动过程中使用 IN_TRANSIT
                    address: currentOrder.address  // 添加地址信息
                }),
                error: function(xhr) {
                    console.error('上传位置失败:', xhr);
                }
            });
        }

        function stopTracking() {
            if (trackingInterval) {
                clearInterval(trackingInterval);
            }
            if (simulationInterval) {
                clearInterval(simulationInterval);
            }
            trackPoints = [];
        }

        // 筛选订单
        function filterOrders(status) {
            loadOrders(status);
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('token');
            window.location.href = '/login';
        }


        // 加载统计数据
        function loadStatistics() {
            $.ajax({
                url: '/api/repairman/statistics',
                type: 'GET',
                success: function(response) {
                    // 更新统计卡片
                    $('#totalOrders').text(response.totalOrders);
                    $('#completedOrders').text(response.completedOrders);
                    $('#pendingOrders').text(response.pendingOrders);
                    $('#todayOrders').text(response.todayOrders);

                    // 更新订单状态分布图表
                    const statusCtx = document.getElementById('orderStatusChart').getContext('2d');
                    new Chart(statusCtx, {
                        type: 'doughnut',
                        data: {
                            labels: ['待接单', '已接单', '维修中', '已完成', '已取消'],
                            datasets: [{
                                data: response.orderStatusDistribution,
                                backgroundColor: [
                                    '#ffc107',
                                    '#17a2b8',
                                    '#007bff',
                                    '#28a745',
                                    '#dc3545'
                                ]
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'right'
                                }
                            }
                        }
                    });
                }
            });
        }

        // 计算两点之间的距离（单位：千米）
        function calculateDistance(lat1, lng1, lat2, lng2) {
            const R = 6371; // 地球半径，单位千米
            const dLat = (lat2 - lat1) * Math.PI / 180;
            const dLng = (lng2 - lng1) * Math.PI / 180;
            const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                    Math.sin(dLng/2) * Math.sin(dLng/2);
            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
            return R * c;
        }

        // 添加手动上传位置的函数
        function uploadCurrentLocation() {
            if (!currentOrder) return;

            // 显示加载提示
            const trackingButton = $('#trackingControls button');
            const originalText = trackingButton.html();
            trackingButton.html('<i class="fas fa-spinner fa-spin"></i> 生成轨迹中...');
            trackingButton.prop('disabled', true);

            // 如果没有起始位置，使用维修工地址的坐标作为起始点
            if (!currentPosition) {
                // 使用百度地图地理编码服务
                const myGeo = new BMap.Geocoder();
                myGeo.getPoint(userAddress, function(startPoint) {
                    if (startPoint) {
                        currentPosition = {
                            lat: startPoint.lat,
                            lng: startPoint.lng
                        };
                        simulateMovement();
                    } else {
                        // 如果无法获取维修工地址坐标，使用默认坐标
                        currentPosition = {
                            lat: 39.915,
                            lng: 116.404
                        };
                        simulateMovement();
                    }
                });
            } else {
                simulateMovement();
            }

            function simulateMovement() {
                const destLat = currentOrder.latitude;
                const destLng = currentOrder.longitude;
                
                // 计算与目的地的距离
                const distance = calculateDistance(
                    currentPosition.lat,
                    currentPosition.lng,
                    destLat,
                    destLng
                );

                // 生成一个随机的中间点，使路径不是直线
                const midPoint = generateMidPoint(
                    currentPosition.lat,
                    currentPosition.lng,
                    destLat,
                    destLng
                );

                // 更新当前位置（添加随机偏移）
                const newPosition = {
                    lat: midPoint.lat + (Math.random() - 0.5) * 0.001,
                    lng: midPoint.lng + (Math.random() - 0.5) * 0.001
                };

                currentPosition = newPosition;

                // 更新地图标记
                const point = new BMap.Point(newPosition.lng, newPosition.lat);
                if (currentMarker) {
                    orderMap.removeOverlay(currentMarker);
                }
                currentMarker = new BMap.Marker(point);
                orderMap.addOverlay(currentMarker);
                
                // 添加到轨迹点数组
                trackPoints.push(point);
                
                // 更新轨迹线
                orderMap.clearOverlays();
                if (destinationMarker) {
                    orderMap.addOverlay(destinationMarker);
                }
                orderMap.addOverlay(currentMarker);
                
                if (trackPoints.length > 1) {
                    const polyline = new BMap.Polyline(trackPoints, {
                        strokeColor: "#18a45b",
                        strokeWeight: 4,
                        strokeOpacity: 0.8
                    });
                    orderMap.addOverlay(polyline);
                }

                // 上传位置到服务器
                $.ajax({
                    url: '/api/repair-track',
                    type: 'POST',
                    contentType: 'application/json',
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('token')
                    },
                    data: JSON.stringify({
                        orderId: currentOrder.id,
                        repairmanId: currentUser.id,
                        latitude: newPosition.lat,
                        longitude: newPosition.lng,
                        status: distance < 0.1 ? 1 : 0,
                        address: currentOrder.address
                    }),
                    success: function() {
                        // 恢复按钮状态
                        trackingButton.html(originalText);
                        trackingButton.prop('disabled', false);
                        // 显示成功提示
                        const toast = $(`<div class="toast align-items-center text-white bg-success" role="alert" aria-live="assertive" aria-atomic="true">
                            <div class="d-flex">
                                <div class="toast-body">
                                    位置上传成功！
                                </div>
                                <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast"></button>
                            </div>
                        </div>`);
                        
                        $('body').append(toast);
                        const bsToast = new bootstrap.Toast(toast);
                        bsToast.show();
                        
                        setTimeout(() => toast.remove(), 3000);
                    },
                    error: function(xhr) {
                        console.error('上传位置失败:', xhr);
                        trackingButton.html(originalText);
                        trackingButton.prop('disabled', false);
                        alert('上传位置失败，请重试');
                    }
                });
            }
        }

        // 生成路径中间点的函数
        function generateMidPoint(startLat, startLng, endLat, endLng) {
            // 计算直线中点
            const midLat = (startLat + endLat) / 2;
            const midLng = (startLng + endLng) / 2;
            
            // 添加随机偏移，使路径不是直线
            // 偏移量基于起点和终点的距离，偏移越大路径越弯曲
            const latDiff = endLat - startLat;
            const lngDiff = endLng - startLng;
            const offset = Math.sqrt(latDiff * latDiff + lngDiff * lngDiff) * 0.2;
            
            return {
                lat: midLat + (Math.random() - 0.5) * offset,
                lng: midLng + (Math.random() - 0.5) * offset
            };
        }

        // 页面加载完成后执行
        $(document).ready(function() {
            orderModal = new bootstrap.Modal(document.getElementById('orderModal'));

            // 优先加载订单列表
            loadOrders('pending'); // 默认显示待接单列表

            // 异步加载其他内容
            Promise.all([
                // 获取用户信息
                new Promise((resolve) => {
                    getUserInfo();
                    resolve();
                }),
                // 加载统计数据
                new Promise((resolve) => {
                    setTimeout(() => {
                        loadStatistics();
                        resolve();
                    }, 200);
                })
            ]);
        });

        // 在页面卸载时清理
        $(window).on('unload', function() {
            stopTracking();
        });
    </script>
</body>
</html> 